/**
 * 
 */
package com.naveejr.dao;

import javax.persistence.NoResultException;
import javax.persistence.Query;

import org.springframework.util.Assert;

import com.naveejr.commons.dao.GenericJpaDao;
import com.naveejr.domain.UserEntity;

/**
 * @author rajeevan
 *
 *         Data access object JPA implementation to work with User entity
 *         database operations
 */
public class UserJpaDao extends GenericJpaDao<UserEntity, Long> implements
		UserDao {

	/**
	 * @param persistentClass
	 */
	public UserJpaDao() {
		super(UserEntity.class);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.naveejr.dao.UserDao#checkAvailable(java.lang.String)
	 */
	public boolean checkAvailable(String userName) {
		Assert.notNull(userName);
		Query query = getEntityManager().createQuery(
				"select count(*) from " + getPersistentClass().getSimpleName()
						+ " u where u.userName = :userName").setParameter(
				"userName", userName);

		Long count = (Long) query.getSingleResult();

		return count < 1;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.naveejr.dao.UserDao#loadUserByUserName(java.lang.String)
	 */
	public UserEntity loadUserByUserName(String userName) {
		Assert.notNull(userName);
		UserEntity user = null;
		Query query = getEntityManager().createQuery(
				"select u from " + getPersistentClass().getSimpleName()
						+ " u where u.userName = :userName").setParameter(
				"userName", userName);
		try {
			user = (UserEntity) query.getSingleResult();
		} catch (NoResultException ex) {
			
		}
		return user;
	}
}
